<template>
  <div class="login-container">
    <el-card class="login-card">
      <h2>部门管理系统登录</h2>
      <el-form :model="form" :rules="rules" ref="loginForm">
        <el-form-item prop="username">
          <el-input v-model="form.userName" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="form.pwd" type="password" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-button type="primary" @click="handleLogin">登录</el-button>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { login } from '@/api/users';
import { ElMessage } from 'element-plus';
import { useStore } from 'vuex';

export default{
  setup(){
    const router=useRouter();
    const loginForm=ref(null);
    const store = useStore();
    const loading = ref(false);
    // 存储用户名和密码
    const form=ref({
      userName:'',
      pwd:''
    });
    // 表单验证规则
    const rules={
      userName:[{ required: true, message: '请输入用户名', trigger: 'blur' }],
      pwd:[{ required: true, message: '请输入密码', trigger: 'blur' }]
    };

    const handleLogin = async () => {
      loginForm.value.validate(async (valid) => {
        if (valid) {
          loading.value = true;
          try {
            const response = await login({
              userName: form.value.userName,
              pwd: form.value.pwd
            });

            if (response) {
              await store.dispatch('login', response.data); // 调用 Vuex 的 login action
              const redirectPath = '/main/department';
              await router.push(redirectPath);
              ElMessage.success('登录成功');
            } else {
              ElMessage.error('用户名或密码错误');
            }
          } catch (error) {
            console.error('登录错误:', error);
            ElMessage.error('登录失败，请稍后重试');
          } finally {
            loading.value = false;
          }
        }
      });
    };

    return {form, rules, loginForm, handleLogin};
  }
};
</script>

<style scoped>
.login-container{
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f5f5;
}
.login-card{
  width: 400px;
  padding: 20px;
}
h2{
  text-align: center;
  margin-bottom: 20px;
}
.el-button{
  width: 100%;
}
</style>